﻿-- =============================================
-- Author:		Taylor Chase
-- Create date: February 8, 2016
-- Description:	Receives the name of a defined view and potentially other commands and returns the result.
-- =============================================
CREATE PROCEDURE [dbo].[ReadDataFromDB] 
	-- Add the parameters for the stored procedure here
	@RequestorEntityID nvarchar(100),
	@CommandName nvarchar(MAX), -- ViewName or EntityID
	@CommandType nvarchar(50) = NULL, -- View, Relationship, Attributes, RelatedEntities
	@Filter nvarchar(MAX) = NULL, -- OR DENIEDATTRIBUTES LIST
	@OrderBy nvarchar(MAX) = NULL,
	@SD datetime = null,
	@ED datetime = null,
	@TD nvarchar(MAX) = '',
	@JSON nvarchar(MAX) = ''

AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	DECLARE @EntityRelationshipList NVARCHAR(MAX),@AttributeList NVARCHAR(MAX)
	DECLARE @SQLQuery NVARCHAR(MAX)


	--IF(SYSTEM_USER <> 'mboadev') BEGIN
	--	SET @RequestorEntityID = NULL
	--	SELECT @RequestorEntityID = EntityID FROM Attributes A INNER JOIN DefinedAttributes DA ON A.AttributeID = DA.AttributeID  
	--	WHERE AttributeName = 'Logon' AND AttributeValueString = SYSTEM_USER
	--	IF @RequestorEntityID IS NULL BEGIN
	--		SELECT 'The user ' + SYSTEM_USER + ' cannot be found in the database.' AS DataError
	--	END
	--END

	IF @CommandName IS NULL BEGIN
		SELECT 'The command given is invalid.' AS DataError
		RETURN
	END

	IF @CommandType IS NULL OR @CommandType = 'View' BEGIN
		SET @SQLQuery = dbo.ConvertRafikiNOSQL('SELECT * FROM {' + @CommandName + '}',@JSON,@SD,@ED,@TD)
		IF NOT @Filter IS NULL BEGIN
			SET @Filter = REPLACE(@Filter,'"','''')
			SET @SQLQuery = @SQLQuery + ' WHERE ' + @Filter
		END
		IF NOT @OrderBy IS NULL
			SET @SQLQuery = @SQLQuery + ' ORDER BY ' + @OrderBy

		IF LEFT(@SQLQuery,6) = 'Error:' BEGIN
			SELECT @SQLQuery AS Error
			RETURN
		END

		EXECUTE (@SQLQuery)
	END ELSE IF @CommandType = 'Relationship' OR @CommandType='RelatedEntities' BEGIN
		-- Move towards calling this as RelatedEntities - not Relationships. A call to relationships could mean something else
		-- Go Get List of Permitted Relationships with RequestorID, chain so far, chain approved so far
		-- Receive back approval flag and relationship list
		-- Pass that to new ViewRelated Entities stored procesure
		-- 
		EXECUTE ReadRelatedEntities @CommandName,'Person'
	END ELSE IF @CommandType = 'Attributes' BEGIN
		SET @SQLQuery = 'SELECT * FROM {' + @CommandName + '}'
		
		EXECUTE GetAttributeNames @SQLQuery
	END ELSE IF @CommandType = 'NOSQL' AND @RequestorEntityID = 0 BEGIN
		SET @SQLQuery = dbo.ConvertRafikiNOSQL(@CommandName,@JSON,@SD,@ED,@TD)
		EXECUTE (@SQLQuery)
	END ELSE
		SELECT 'The command given is invalid.' AS DataError
	RETURN 0


END